﻿
using AutoMapper;
using MediatR;
using SmartCity.ProcessEngine.Api.Write.Application.Command.FormCategory;
using SmartCity.ProcessEngine.Domain.Entities;
using SmartCity.ProcessEngine.ErrorCode;
using SmartCity.ProcessEngine.Infrastructure.Interface;
using Yitter.IdGenerator;

namespace SmartCity.ProcessEngine.Api.Write.Application.CommandHandler.FormCategory
{
    /// <summary>
    /// 更新表单类别
    /// </summary>
    public class UpdateFormCategoryHandler : IRequestHandler<UpdateFormCategoryCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<FormCategoryModel> formCategoryRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateFormCategoryHandler> logger;

        public UpdateFormCategoryHandler(IBaseRepository<FormCategoryModel> formCategoryRepo,IMapper mapper,ILogger<UpdateFormCategoryHandler> logger )
        {
            this.formCategoryRepo = formCategoryRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateFormCategoryCommand request, CancellationToken cancellationToken)
        {
            var entity =await formCategoryRepo.GetModel(request.Id);//根据id查找到实体
            if (entity == null){
                return new ApiResult<int>().Fail("您要修改的表单类别不存在");
            }

           //var model = mapper.Map<FormCategoryModel>(request);//把请求命令通过automapper 转成实体
            entity = mapper.Map(request,entity);//把请求命令里的属性覆盖到查找到的实体属性

             
            int r = await formCategoryRepo.UpdateAsync(entity);

            if (r > 0)
            {
                return new ApiResult<int>().Success("更新表单类别成功", r);
            }
            else {
                return new ApiResult<int>().Fail("更新表单类别失败");
            }
        }
    }
}
